package com.ry.est.exception;

import com.ry.est.dto.CommonResult;
import com.ry.est.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;

/**
 * 改成响应体
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 项目中系统异常的统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public CommonResult<Void> handleException(Exception e){
        log.error("系统异常",e);
        return ResultUtil.fail("-1",e.getMessage());

    }

    /**
     * 对控制器 对象参数 使用jsr-303注解进行验证出现异常时（参数不符合预期）的处理
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public CommonResult<Void> handleException(BindException e){
        log.warn("绑定异常",e);
        List<ObjectError> allErrors = e.getAllErrors();
        StringJoiner joiner = new StringJoiner(";");
        for (ObjectError error : allErrors) {
            joiner.add(error.getDefaultMessage());
        }
        return ResultUtil.fail("-1",joiner.toString());
    }
    /**
     * 对控制器 单个参数 使用jsr-303注解进行验证出现异常时（参数不符合预期）的处理
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public CommonResult<Void> handleException(ConstraintViolationException e){
        log.warn("参数异常",e);
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        StringJoiner joiner = new StringJoiner(";");
        for (ConstraintViolation violation : constraintViolations) {
            joiner.add(violation.getMessage());
        }
        return ResultUtil.fail("-1",joiner.toString());
    }
}
